package com.ibm.iisp.common.rest;

import java.util.HashMap;
import java.util.Locale;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import com.ibm.iisp.common.exception.I18nAppException;

/**
 * 类作用：把应用中没有捕捉的异常转换成适合展示的异常返回到前台框架
 * 
 * @author JohnnyZhou@cn.ibm.com
 */
@Component
public class RestExceptionMapper extends AbstractHandlerExceptionResolver {// implements ExceptionMapper<Throwable> {
	Logger log = LoggerFactory.getLogger(getClass());
	@Inject MessageSource messageSource;

	// public Response toResponse(Throwable throwable) {
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver#doResolveException(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
		Exception throwable) {
		log.debug("Error Occurred!", throwable);
		// if (throwable instanceof WebApplicationException) {
		// return ((WebApplicationException)throwable).getResponse();
		// }
		HashMap<String, Object> errorMessage = new HashMap<>();
		errorMessage.put("type", throwable.getClass().getSimpleName());
		errorMessage.put("defaultMessage", throwable.getMessage());
		if (throwable.getCause() != null){
			errorMessage.put("cause", throwable.getCause().getMessage());
		}
		if (throwable instanceof I18nAppException) {
			I18nAppException i18nException = (I18nAppException)throwable;
			errorMessage.put("code", i18nException.getErrorCode());
			String messageKey = i18nException.getMessageKey();
			errorMessage.put("messageKey",messageKey);
			Locale lc = LocaleContextHolder.getLocale();
			String localizedMessage = messageSource.getMessage(messageKey, i18nException.getArgs(), null, lc);
			if (localizedMessage != null) {
				errorMessage.put("localizedMessage", localizedMessage);
			}
		}
		return null;
		// return RuntimeDelegate.getInstance().createResponseBuilder().status(500).entity(errorMessage).build();
	}

}
